#ifndef MODBUSMASTER_H
#define MODBUSMASTER_H
#include <QObject>
#include <QModbusServer>
#include <QModbusRtuSerialSlave>
#include <QModbusTcpServer>
#include <QSerialPort>
#include <QMainWindow>
#include "database.h"

namespace Ui {
class modbusMaster;
}


class modbusMaster : public QMainWindow
{
    Q_OBJECT

public:
    explicit modbusMaster(QWidget *parent = 0);
    ~modbusMaster();

    //@brief:初始化串口modbusaster
    //@param:端口 波特率 数据位 校验位 停止位
    //@ret: QModbusRtuSerialSlave对象构建成功返回 1
    //@birth:2019.4.17
    bool initModbusSerialMaster(QString portName, qint32 baudRate, QSerialPort::DataBits dataBits,
                         QSerialPort::Parity parity, QSerialPort::StopBits stopBits);


    //@brief:初始化 TCP modbusaster
    //@param: IP地址 端口
    //@ret: QModbusTcpServer对象构建成功返回 1
    //@birth:2019.4.17
    bool initModbusNetworkMaster(QString address,int port);


    //@brief:Connects the device to the Modbus network.
    //@param:
    //@ret: 成功返回 true
    //@birth:2019.4.17
    bool connectDevice();

    DataBase Db_modbus;

    enum modbusConnection
    {
        Serial,
        Tcp
    };

signals:

    //寄存器值发生改变
    void registerData_signal(int address,int value);
    //发生错误
    void error_signal(QString errorString);
    /*state :1 connect ,0:unconnect
    *状态发生改变
    */
    void stateChanged_signal(int state);


public slots:

private slots:

    //@brief:从客户端接收数据
    //@param:数据类型 ，起始地址，个数
    //@ret: void
    //@birth:2019.4.17
    void updateData(QModbusDataUnit::RegisterType table, int address, int size);


    void handleDeviceError(QModbusDevice::Error newError);

    void onStateChanged(int state);

    void on_connectButton_clicked();

    void on_writeButton_clicked();

    void on_dataButton_clicked();

private:
    modbusConnection m_mode;
    QModbusServer* m_master;
    Ui::modbusMaster *ui;
    DataBase *data_base;//用于显示数据库窗口表格

};

  // DataBase *data_base;

    union server
    {
        float Data[6];
        quint16 receive_data[13];
    };

extern union server Udata;

#endif // MODBUSSLOVE__H

